package Agent;

import java.util.Vector;

import org.w3c.dom.views.AbstractView;

import Env.Car;
import Env.Environment;
import Env.Graph;

public class SpeedNutAgent extends AbstractAgent{
	
	private int[] visits;

	public SpeedNutAgent(int start,  Environment env) {
		super(start, 0, env);
		visits=new int[env.getGraph().n+1];
	}

	@Override
	protected void chooseCarAndVertex() throws Exception {
		Graph g=env.getGraph();
		Vector<Integer> connected= g.getAllConnected(position);
		Vector<Car> cars=env.getCars(position);
		if (checkForEffCar(cars)){
			chosenVertex= maxEdge(g, connected);
			chosenCar=maxEffCar(cars);
		}else {
			chosenVertex=maxNonFloodedEdge(g, connected);
			chosenCar=maxCar(cars);
			if (chosenCar!=null)
				visits[chosenVertex]++;
		}
	}
	
	public void move() throws Exception{
		super.move();
		if (visits[position]==3){
			stopFlag=true;
		}
		
	}

	

	private Car maxCar(Vector<Car> cars) {
		Car ans=null;
		int speed=0;
		for(Car i:cars){
			if (i.getSpeed()>speed){
				ans=i;
				speed=i.getSpeed();
			}
		}
		return ans;
	}

	private Car maxEffCar(Vector<Car> cars) {
		Car ans=null;
		int speed=0;
		for(Car i:cars){
			if (i.getEff()>0 && i.getSpeed()>speed){
				ans=i;
				speed=i.getSpeed();
			}
		}
		return ans;
	}

	private boolean checkForEffCar(Vector<Car> cars) {
		for(Car i:cars){
			if (i.getEff()>0) return true;
		}
		return false;
	}

	private int maxEdge(Graph g, Vector<Integer> connected) throws Exception {
		int max=-1;
		int maxV=-1;
		for (Integer i:connected){
			if (history.lastElement()==i)
				continue;
			if (g.getEdgeCost(position, i)>max){
				max=g.getEdgeCost(position, i);
				maxV=i;
			}
		}
		return maxV;
	}
	
	private int maxNonFloodedEdge(Graph g, Vector<Integer> connected) throws Exception {
		int max=-1;
		int maxV=-1;
		
		for (Integer i:connected){
			if (!history.isEmpty()&& history.lastElement()==i||g.isEdgeFlooded(position, i))
				continue;
			if (g.getEdgeCost(position, i)>max){
				max=g.getEdgeCost(position, i);
				maxV=i;
			}
		}
		return maxV;
	}
	

}
